package com.gxa.ehome.controller;

import com.gxa.ehome.busiCodeEnum.ErrorCode;
import com.gxa.ehome.exception.BusinessException;
import com.gxa.ehome.util.MapUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;


@ControllerAdvice
@ResponseBody
public class ExceptionController {
   // @ExceptionHandler(Throwable.class) 捕获所有的异常 都会被该方法拦截
   // @ExceptionHandler(value = Throwable.class)
    @ExceptionHandler(value = {Throwable.class})
    public Map<String,Object> exceptionHandle(Throwable throwable){
        System.out.println(throwable);
        //业务类型异常:给前端code/desc,给用户看

        //系统异常:500的状态告诉前端开发人员,给用户提示
        //系统发生了未知问题请稍后再试
        //再把系统完整的异常信息记录日志.

        MapUtil mapUtil=new MapUtil();

        if(throwable instanceof BusinessException){
            ErrorCode errorCode = ((BusinessException) throwable).getErrorCode();
            mapUtil.setCode(errorCode.getCode());
            mapUtil.setMsg(errorCode.getDesc());

            //System.out.println("ExceptionController exceptionHandle  BusinessException");
        }else{
            System.out.println("system Exception");
            //给前端看
            mapUtil.setCode("500");
            mapUtil.setMsg("系统发生未知问题,请稍后再试");
            //操作日志:将异常的完整信息记录到日志文件

            ((Exception) throwable).getMessage();
            ((Exception) throwable).toString();
            StackTraceElement[] stackTrace = ((Exception) throwable).getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {

            }


        }



        System.out.println("ExceptionController exceptionHandle ");
        return mapUtil.getValues();


    }

}